package com.sh15tech.mp.weixin.thread;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;

import com.sh15tech.mp.weixin.modal.WxUserDetail;
import com.sh15tech.mp.weixin.scan.WxSender;

public class WxSynUserThread implements Runnable{

	private Logger log = LogManager.getLogger(getClass());
	
	private JdbcTemplate jdbcTemplate;
	
	public WxSynUserThread(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public void run() {
		
		while(true){
			
			jdbcTemplate.execute("truncate table t_wx_user");
			
			List<WxUserDetail> users = WxSender.getUsers();
			
			if(!users.isEmpty()){
				
				List<String> sql = new ArrayList<>();
				
				for(WxUserDetail str : users){
					sql.add("insert into t_wx_user (openid, nickname) values ('"+str.getOpenid()+"','"+str.getNickname()+"')");
				}
				
				int[] result = jdbcTemplate.batchUpdate(sql.toArray(new String[sql.size()]));
				for(int res : result){
					log.info("execute update result : "+res);
				}
			}
			
			try {
				Thread.sleep(1000*60*60);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
